package com.jwgf.spi;

import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

public class SpiManager {
	private static Messenger sendMessenger;
	private static Messenger recvMessenger;
	private static SpiManager instance = new SpiManager();

	private static boolean isComOK = false;

	private SpiManager() {

	}

	public static void createInstance(Messenger sendMsger, Messenger recvMsger) {
		sendMessenger = sendMsger;
		recvMessenger = recvMsger;
	}

	public static SpiManager getInstance() {
		if (sendMessenger != null && recvMessenger != null) {
			return instance;
		} else {
			return null;
		}
	}

	public void open() {
		Message msg = Message.obtain();
		msg.what = SPIInterface.OPEN;
		msg.replyTo = recvMessenger;
		send(msg);
	}

	public void write(byte[] data) {
		Bundle bd = new Bundle();
		bd.putByteArray(SPIInterface.DATA, data);

		Message msg = Message.obtain();
		msg.what = SPIInterface.WRITE;
		msg.setData(bd);
		send(msg);
	}

	public void read(int timeout) {
		Bundle bd = new Bundle();
		bd.putInt(SPIInterface.TIMEOUT, timeout);
		Message msg = Message.obtain();
		msg.what = SPIInterface.READ;
		msg.setData(bd);
		send(msg);
	}

	public byte[] read(Message msg) {
		Bundle bd = msg.getData();
		byte[] recvMsg = bd.getByteArray(SPIInterface.DATA);
		if (recvMsg[0] == 0) {
			isComOK = true;
		} else {
			isComOK = false;
		}
		return recvMsg;
	}

	public void close() {
		Message msg = Message.obtain();
		msg.what = SPIInterface.CLOSE;
		send(msg);
	}

	private void send(Message msg) {
		try {
			sendMessenger.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public static boolean isComOK() {
		return isComOK;
	}
}
